package com.beiding.fastmock.config;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import jdk.nashorn.api.scripting.ScriptObjectMirror;
import org.springframework.boot.jackson.JsonComponent;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 丁常磊
 * @date 2021/7/14 11:09
 */

@JsonComponent
public class ScriptConfig {

    /**
     * 对ScriptObjectMirror序列化兼容
     */
    public static class Serialize extends JsonSerializer<ScriptObjectMirror> {
        @Override
        public void serialize(ScriptObjectMirror value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
            if (value.isArray()) {
                Object[] arr = new Object[value.size()];
                value.forEach((k, v) -> {
                    int index = Integer.parseInt(k);
                    arr[index] = v;
                });
                gen.writeObject(arr);
            } else {
                Map<String,Object> map = new HashMap<>(value);
                gen.writeObject(map);
            }
        }
    }

}
